let bgm;
let isPlaying = false; // 新增变量，用于记录音乐是否正在播放
let audioContext = new (window.AudioContext || window.webkitAudioContext)();
let gainNode = audioContext.createGain(); // 创建增益节点用于调节音量

let music_json = {
    "button": null,
    "pass": null,
    "rob": null,
};

// 卢本伟语音包
let lubenwei = ["other1", "other2", "other3", "other4", "other5", "other6"];

// 获取音效函数
function gainplaySound(url) {
    return new Promise((resolve, reject) => {
        var request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.responseType = 'arraybuffer';
        request.onload = function () {
            audioContext.decodeAudioData(request.response, function (buffer) {
                var source = audioContext.createBufferSource();
                source.buffer = buffer;
                source.connect(gainNode); // 连接到增益节点
                gainNode.connect(audioContext.destination); // 增益节点连接到音频上下文
                resolve(source);
            }, function (error) {
                console.log('音频解码错误: ', error);
                reject(error);
            });
        };
        request.send();
    });
}

// 加载语音包
for (let i = 0; i < lubenwei.length; i++) {
    gainplaySound('../resources/music/' + lubenwei[i] + '.mp3')
        .then((source) => {
            music_json[lubenwei[i]] = source.buffer;
        })
        .catch((error) => {
            console.log('获取音频资源出错：', error);
        });
}

// 获取背景音效
gainplaySound('../resources/music/game_background.mp3')
    .then((source) => {
        source.loop = true; // 设置循环播放
        bgm = source;
    })
    .catch((error) => {
        console.log('获取音频资源出错：', error);
    });

// 获取按钮音效
gainplaySound('../resources/music/button.mp3')
    .then((source) => {
        music_json["button"] = source.buffer;
    })
    .catch((error) => {
        console.log('获取音频资源出错：', error);
    });

// 获取抢地主音效
gainplaySound('../resources/music/rob_master.mp3')
    .then((source) => {
        music_json["rob"] = source.buffer;
    })
    .catch((error) => {
        console.log('获取音频资源出错：', error);
    });

// 获取跳过音效
gainplaySound('../resources/music/pass.mp3')
    .then((source) => {
        music_json["pass"] = source.buffer;
    })
    .catch((error) => {
        console.log('获取音频资源出错：', error);
    });

// 播放/暂停背景音乐
function playbgm() {
    if (bgm) {
        if (isPlaying) {
            bgm.stop(0);
            isPlaying = false;
            $("#bgm i").removeClass("fa-pause").addClass("fa-music"); // 切换图标
        } else {
            const newSource = audioContext.createBufferSource();
            newSource.buffer = bgm.buffer;
            newSource.connect(gainNode); // 连接到增益节点
            newSource.start(0);
            isPlaying = true;
            bgm = newSource; // 更新bgm变量指向新的实例
            $("#bgm i").removeClass("fa-music").addClass("fa-pause"); // 切换图标
        }
    }
}

// 播放音效
function playsound(str_key) {
    if (music_json[str_key]) {
        const source = audioContext.createBufferSource();
        source.buffer = music_json[str_key];
        source.connect(gainNode); // 连接到增益节点
        source.start(0);
        source.onended = function () {
            source.disconnect();
            source.buffer = null;
        };
    }
}

// 音量调节
$(document).ready(function () {
    $("#volume-slider").on("input", function () {
        const volume = parseFloat($(this).val());
        gainNode.gain.value = volume; // 设置音量
    });
});